const title = require('../module/title')

// 增加标题
const create_title = async (ctx, next) => {
    try {
        // 如果是post请求---ctx.request.body，如果是get请求---ctx.request.query
        //1. 获取前端的入参值
       const {content} = ctx.request.body

       //2. 进行数据库的操作
       const addTitleRes = await title.create({
        content
       })

       if(addTitleRes){
           ctx.body = {
               code: 0,
               msg: '标题添加成功',
               data: addTitleRes
           }
       }else{
        ctx.body = {
            code: -1,
            msg: '标题添加失败',
            data: ''
        }
       }
    } catch (e) {
        ctx.body = {
            code: -1,
            msg: `标题添加失败，失败原因${e}`,
            data: ''
        }
    }
}

// 查找标题
const search_title = async (ctx, next) => {
    try {
        const searchTitleRes = await title.find();

        if(searchTitleRes){
            ctx.body = {
                code: 0,
                msg: '标题查找成功',
                data: searchTitleRes
            }
        }else{
         ctx.body = {
             code: -1,
             msg: '标题查找失败',
             data: ''
         }
        }
    } catch(e) {
        ctx.body = {
            code: -1,
            msg: `标题查找失败,失败原因${e}`,
            data: ''
        }
    }
}

// 删除标题
const del_title = async (ctx, next) => {
    try {
        const {content} = ctx.request.body
        const delTitleRes = await title.deleteOne({content})

        if(delTitleRes){
            ctx.body = {
                code: 0,
                msg: '标题删除成功',
                data: delTitleRes
            }
        }else{
            ctx.body = {
                code: -1,
                msg: '标题删除失败',
                data: ''
            }
        }
    } catch(e) {
        ctx.body = {
            code: -1,
            msg: `标题删除失败,失败原因${e}`,
            data: ''
        }
    }
}

const change_title = async (ctx, next) => {
    try{
        const {content,newContent} = ctx.request.body
        const changeTitleRes = await title.updateOne({content},{content:newContent})

        if(changeTitleRes){
            ctx.body = {
                code: 0,
                msg: '标题修改成功',
                data: changeTitleRes
            }
        } else {
            ctx.body = {
                code: -1,
                msg: '标题修改失败',
                data: ''
            }
        }
    }catch(e){
        ctx.body = {
            code: -1,
            msg: `标题修改失败,失败原因${e}`,
            data: ''
        }
    }
}

// 进行接口的注册
module.exports = {
    'POST /addTitle' : create_title,
    'GET /searchTitle' : search_title,
    'POST /delTitle': del_title,
    'POST /changeTitle': change_title
}